# -*- coding:utf-8 -*-
__author__ = 'lixin'
import socket
import time
import sys
import urllib2
import os
import stat
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler
udpport=8712
def myIP():
    r=os.popen(" ifconfig |grep inet |awk '{print $2}' |awk -F ':' '{print $2}' ")
    text=r.read()
    return text.replace('\n',',')


def udpBroadcast():
    '''
    发送udp广播包，告诉网内主机，我是树莓派
    send udp message to lan,I am Raspberry pi
    :return:
    '''
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
    i=6
    while i>0:
        try:
            s.sendto('iamrpi',('255.255.255.255',udpport))
        except Exception ,ex:
            print "error:"+ex.message
        i=i-1
        time.sleep(2)
    return
def tcpHello(host,port):
    '''
    指定具体的tcp接收地址，向其告知自己是树莓派
    :param host:
    :param port:
    :return:
    '''
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    i=3
    while i>0:
        try:
            s.connect((host,int(port)))
            s.sendall('iamrpi')
            s.close()
            break
        except Exception,ex:
            print('error:'+ex.message)
        i=i-1
        time.sleep(3)
def webHello(url):
    i=3
    while i>0:
        try:
            req=urllib2.Request(url,data='ip='+myIP())
            resp=urllib2.urlopen(req)
            print(resp.read())
            break
        except Exception,ex:
            print('webHello error:'+ex.message)
        i=i-1

def yeelink(url,apikey):
    i=3
    while i>0:
        try:
            data='{"key":"%s","value":{"time":"%s","ip":"%s"}}' % (time.ctime(),time.strftime('%Y-%m-%d %H:%M:%S'),myIP())
            req=urllib2.Request(url)
            req.add_data(data)
            req.add_header('U-ApiKey',apikey)

            resp=urllib2.urlopen(req)
            print(resp.read())
            break
        except Exception,ex:
            print('yeelink error:'+ex.message)
        i=i-1
def tcpListen(port):
    s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind(('',port))
    s.listen(5)
    print('begin waiting tcp port:'+str(port))
    while True:
        client,addr=s.accept()
        msg=client.recv(1024)
        print('received:'+msg+';from:'+addr[0])
        if msg.find('iamrpi')>-1:
            print('find one Raspberry pi:'+addr[0])
        client.close()
def udpListen():
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.bind(('',udpport))
    print('begin waiting udp port:'+str(udpport))
    while True:
        data,addr=s.recvfrom(1024)
        s.sendto('ok',addr)
        print('received:'+data+';from:'+addr[0])
        if data.find('iamrpi')>-1:
            print("find one Raspberry pi:"+addr[0])
class PostHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        form=cgi.FieldStorage(fp=self.rfile,headers=self.headers,environ={'REQUEST_METHOD':'POST','CONTENT_TYPE':self.headers['Content-Type'],})
        self.send_response(200)
        self.end_headers()
        self.wfile.write('ok')
        print('one connecting')
        for field in form.keys():
            field_item=form[field]
            if field=='ip':
                print('find one Raspberry pi,IP:'+field_item.value)
        return

if __name__ == '__main__':
    if len(sys.argv)>1 and  sys.argv[1]=='test':
        # print ('begin test udp send,port:'+str(udpport))
        # udpBroadcast()
        # print('completed test udp send')
        # print ('begin test tcpHello')
        # host=raw_input('Enter host:')
        # port=raw_input('Enter port:')
        # tcpHello(host,port)
        # print('completed test tcp hello')
        # print('begin test myIP')
        # print myIP()
        yeelink('http://api.yeelink.net/v1.1/device/340446/sensor/377052/datapoints','597fdba7c1820ad6e08c08091b6b9896')
        print('completed test myIP')
    elif len(sys.argv)>1 and sys.argv[1]=='install':
        print 'chose method.eg:1,2,4'
        print('1:udp\n2:tcp\n3:web\n4:yeelink')
        chose=raw_input("your chose(default 1,2,3,4):")
        if chose=='':
            chose='1,2,3,4'
        fp=os.path.join(sys.path[0],sys.argv[0])
        rpifile=open('/etc/init.d/RPIWhere.sh',mode='w')
        rpifile.write('''
#!/bin/sh
### BEGIN INIT INFO
# Provides:          RPIWhere.sh
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4
# Default-Stop:
# Short-Description: starts the RPIWhere daemon
# Description:       starts RPIWhere using start-stop-daemon
### END INIT INFO
        ''')

        if chose.find('1')>-1:
            rpifile.write('python '+fp+' 1\n')
        if chose.find('2')>-1:
            ip=raw_input('请输入tcp监听的ip:')
            port=raw_input('请输入tcp监听的端口:')
            rpifile.write('python '+fp+' 2 '+ip+' '+port+'\n')
        if chose.find('3')>-1:
            url=raw_input('请输入post的网址：')
            rpifile.write('python '+fp+' 3 '+url+'\n')
        if chose.find('4')>-1:
            api=raw_input('请输入yeelink api key:')
            url2=raw_input('请输入yeelink 设备API地址：')
            rpifile.write('python '+fp+' 4 '+url2+' '+api+'\n')
        rpifile.close()
        os.chmod('/etc/init.d/RPIWhere.sh',stat.S_IRWXU|stat.S_IRWXG|stat.S_IXOTH|stat.S_IRWXG)
        os.system('update-rc.d RPIWhere.sh start 999 2 3 4 ')
    elif len(sys.argv)>1 and sys.argv[1]=='1':
        udpBroadcast()
    elif len(sys.argv)>1 and sys.argv[1]=='2':
        tcpHello(sys.argv[2],sys.argv[3])
    elif len(sys.argv)>1 and sys.argv[1]=='3':
        webHello(sys.argv[2])
    elif len(sys.argv)>1 and sys.argv[1]=='4':
        yeelink(sys.argv[2],sys.argv[3])
    elif len(sys.argv)>1 and sys.argv[1]=='remove':
        os.system('sudo update-rc.d RPIWhere.sh remove')
        os.remove('/etc/init.d/RPIWhere.sh')
        print('remove ok')
    elif len(sys.argv)>1 and sys.argv[1]=='udplisten':
        udpListen()
    elif len(sys.argv)>1 and sys.argv[1]=='tcplisten':
        p=raw_input('Enter tcp listen port:')
        tcpListen(int(p))
    elif len(sys.argv)>1 and sys.argv[1]=='weblisten':
        from BaseHTTPServer import HTTPServer
        p=raw_input('Enter web listen port:')
        server=HTTPServer(('',int(p)),PostHandler)
        print ('begin web server')
        server.serve_forever()




